<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, watch, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { createChatWebSocket, type ChatMessage } from '@/utils/chat'
import { 
  ElContainer, 
  ElAside, 
  ElMain, 
  ElCard, 
  ElInput, 
  ElButton, 
  ElScrollbar, 
  ElMessage,
  ElBadge,
  ElEmpty
} from 'element-plus'
import LoadingSpinner from '@/components/LoadingSpinner.vue'
import { ar } from 'element-plus/es/locales.mjs'
import api from '@/utils/api'
import { authService } from '@/services/apiService'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// WebSocket连接
const chatWebSocket = ref<ReturnType<typeof createChatWebSocket> | null>(null)
const newMessage = ref('')
const chatContainer = ref<HTMLDivElement | null>(null)
const loadingHistory = ref(false)
const isConnecting = ref(false) // 连接或认证中

// 计算属性：过滤会话列表
const filteredConversations = computed(() => {
  if (!chatWebSocket.value) return []

  return chatWebSocket.value.contacts.map(contact => ({
    id: contact.id,
    username: contact.username, 
    avatar: contact.avatar,
    unreadCount: contact.unread_count,
  }))
})

// 计算属性：当前选中的会话ID
const selectedConversationId = computed(() => {
  return chatWebSocket.value?.activeContact?.id || null
})

// 计算属性：当前消息列表 - 从WebSocket实例获取
const messages = computed(() => {
  if (!chatWebSocket.value) return []
  // 过滤出当前选中联系人的消息
  return chatWebSocket.value.messages.filter(msg => {
    const activeContact_v = chatWebSocket.value?.activeContact
    if (!activeContact_v) return false
    return msg.receiverId === activeContact_v.id || msg.senderId === activeContact_v.id
  })
})
// 监听活动会话的变化
onMounted(() => {
  
  // 连接到WebSocket
  initializeWebSocket()

  // 检查是否有已选中的聊天目标（从别的界面选中联系卖家跳转过来）
  console.log('检查本地存储中的聊天目标')
  const targetUser = localStorage.getItem('chatTargetUser')
  if (targetUser) {
    const { receiverId, username } = JSON.parse(targetUser)
    // 检查是否尝试与自己聊天
    if (receiverId === userStore.userInfo.id) {
      ElMessage.warning('不能与自己聊天')
      localStorage.removeItem('chatTargetUser')
      return
    }
    selectConversation(receiverId, username)

    localStorage.removeItem('chatTargetUser')
  }
})

// 初始化WebSocket连接
const initializeWebSocket = () => {
  isConnecting.value = true
  try {
    chatWebSocket.value = createChatWebSocket()
    if (chatWebSocket.value) {
      chatWebSocket.value.connect()
    }

    console.log('聊天WebSocket初始化完成')
    // 监听WebSocket连接状态
    watch(() => chatWebSocket.value?.status,(newStatus) => {
      console.log('newStatus状态变化:', newStatus)
      if (newStatus === 'connected') {
        isConnecting.value = false
        // 连接成功后，可以选择第一个联系人
        if (chatWebSocket.value?.contacts && chatWebSocket.value.contacts.length > 0) {
          // 这里可以根据需要选择一个默认联系人，或者等待用户点击
          
        }
      } else if (newStatus === 'error' || newStatus === 'disconnected') {
        isConnecting.value = false
      }
    })
    console.log('WebSocket状态监听已设置')

    // 监听WebSocket消息变化，用于滚动
    watch(() => chatWebSocket.value?.messages, () => {
      nextTick(() => {
        scrollToBottom()
      })
    }, { deep: true })

  } catch (error) {
    console.error('初始化聊天WebSocket失败:', error)
    isConnecting.value = false
    ElMessage({
      message: error instanceof Error ? error.message : '聊天初始化失败',
      type: 'error',
      duration: 3000,
      showClose: true
    })
  }
}


// 选择会话
const selectConversation = async (receiverId: number, username: string) => {
  // 检查是否尝试与自己聊天
  if (receiverId === userStore.userInfo.id) {
    ElMessage.warning('不能与自己聊天')
    return
  }
  
  if (!chatWebSocket.value) {
    console.error('WebSocket未初始化')
    return
  }

  const existingContactIndex = chatWebSocket.value.contacts.findIndex(
    contact => contact.id === receiverId
  )
  // 如果不存在，创建新的联系人对象并添加到contacts
  const response = await authService.getUserAvatarURL(receiverId)
  let avatar = response.avatar || '/media/images/default_avatar.png'
  console.log('新建会话获取到的头像URL:', avatar)
  if (existingContactIndex === -1) {
    const newContact = {
      id: receiverId,
      username: username,
      avatar: avatar, 
      unread_count: 0 
    }
    chatWebSocket.value.contacts.push(newContact)
  }
  // 设置当前选中的联系人
  chatWebSocket.value.activeContact = { id: receiverId, username: username }
  
  // 清空当前消息列表
  chatWebSocket.value.messages = []

  // 加载历史消息
  loadingHistory.value = true
  try {
    // 确保 loadHistory 方法正确实现，不会重新连接
    chatWebSocket.value.loadHistory(receiverId)
  } catch (error) {
    console.error('加载历史消息失败:', error)
    loadingHistory.value = false
  }
  // 滚动到底部
  nextTick(() => {
    scrollToBottom()
    loadingHistory.value = false
  })
}

// 发送消息
const sendMessage = () => {
  if (newMessage.value.trim() === '' || !chatWebSocket.value) {
    return
  }

  const receiverId = chatWebSocket.value.activeContact?.id

  if (!receiverId) {
    ElMessage({
      message: '请选择一个聊天对象',
      type: 'warning',
      duration: 3000,
      showClose: true
    })
    return
  }

  const success = chatWebSocket.value.sendMessage(newMessage.value, receiverId)
  if (success) {
    newMessage.value = ''
  } else {
    ElMessage({
      message: '消息发送失败，请检查网络连接',
      type: 'error',
      duration: 3000,
      showClose: true
    })
  }
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (chatContainer.value && messages.value.length > 0) {
      chatContainer.value.scrollTop = chatContainer.value.scrollHeight;
    }
  });
}

// 返回首页
const goBackToHome = () => {
  router.push('/')
}

// 组件卸载时断开连接
onUnmounted(() => {
  if (chatWebSocket.value) {
    chatWebSocket.value.disconnect()
  }
})

</script>

<template>
  <div class="chat-main-container">
    <div class="main-layout">
      <!-- 左侧会话列表 -->
      <div class="conversation-list">
        <div class="conversation-list-card">
          <div class="conversation-header">
            <h2>我的聊天</h2>
            <el-button type="primary" @click="goBackToHome" size="small">返回首页</el-button>
          </div>
          
          <div class="conversation-list-body">
            <div 
              v-for="conversation in filteredConversations" 
              :key="conversation.id" 
              class="conversation-item"
              :class="{ active: conversation.id === selectedConversationId }"
              @click="selectConversation(conversation.id, conversation.username)"
            >
              <div class="conversation-card">
                <div class="conversation-item-content">
                  <div class="conversation-info">
                    <h3>{{ conversation.username }}</h3>
                  </div>
                  <div class="conversation-meta">
                    <el-badge 
                      v-if="conversation.unreadCount > 0" 
                      :value="conversation.unreadCount" 
                      type="danger"
                      :max="99"
                    />
                  </div>
                </div>
              </div>
            </div>
            
            <div v-if="filteredConversations.length === 0" class="no-conversations">
              <el-empty description="暂无聊天记录" />
            </div>
          </div>
        </div>
      </div>
      
      <!-- 右侧聊天区域 -->
      <div class="chat-area">
        <div v-if="chatWebSocket?.activeContact" class="chat-container">
          <div class="chat-header">
            <h2>
              与{{ chatWebSocket?.activeContact.username }}的聊天
              <span v-if="isConnecting" class="connecting-status">(连接中...)</span>
            </h2>
          </div>
          
          <!-- 消息显示区域 -->
          <div class="chat-messages-container">
            <div ref="chatContainer" class="chat-messages">
              <!-- 加载历史消息提示 -->
              <div v-if="loadingHistory" class="loading-indicator">
                <LoadingSpinner message="加载聊天记录..." />
              </div>
              
              <!-- 消息列表 -->
              <div 
                v-for="(message, index) in messages" 
                :key="index" 
                class="message"
                :class="{ 
                  'own-message': message.senderId === userStore.userInfo.id,
                  'other-message': message.senderId !== userStore.userInfo.id 
                }"
              >
                <div class="message-content">
                  <div class="content">{{ message.content }}</div>
                  <div class="timestamp">
                    {{ message.sendTime ? new Date(message.sendTime).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : '' }}
                  </div>
                </div>
              </div>
              
              <!-- 无消息提示 -->
              <div v-if="!loadingHistory && messages.length === 0" class="no-messages">
                <p>暂无聊天记录</p>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 独立的聊天输入区域 -->
        <div class="chat-input-area">
          <div class="chat-input">
            <el-input 
              v-model="newMessage" 
              placeholder="输入消息..." 
              @keyup.enter="sendMessage"
            >
              <template #append>
                <el-button @click="sendMessage" :disabled="isConnecting">发送</el-button>
              </template>
            </el-input>
          </div>
        </div>
        
        <!-- 未选择会话时的提示 -->
        <div v-if="!chatWebSocket?.activeContact" class="no-conversation-selected">
          <el-empty description="请选择一个聊天会话开始对话">
            <el-button type="primary" @click="goBackToHome">返回首页</el-button>
          </el-empty>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.chat-main-container {
  height: calc(100vh - 120px);
  width: 100%;
  margin: 0;
  padding: 0;
  display: flex;
}

.main-layout {
  display: flex;
  width: 100%;
  height: 100%;
}

/* 左侧会话列表 */
.conversation-list {
  width: 300px;
  height: 100%;
  padding: 0 10px 0 0;
  display: flex;
  flex-direction: column;
  border-right: 1px solid #eee;
}

.conversation-list-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.conversation-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
  flex-shrink: 0;
}

.conversation-header h2 {
  margin: 0;
  color: #333;
  font-size: 1.2em;
}

.conversation-list-body {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
}

.conversation-item {
  cursor: pointer;
  margin-bottom: 10px;
}

.conversation-item:last-child {
  margin-bottom: 0;
}

.conversation-card {
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  transition: all 0.2s;
}

.conversation-item:hover .conversation-card {
  border-color: #007bff;
}

.conversation-item.active .conversation-card {
  border-color: #007bff;
  background-color: #f0f8ff;
}

.conversation-item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.conversation-info {
  flex: 1;
  min-width: 0;
}

.conversation-info h3 {
  margin: 0 0 5px 0;
  color: #333;
  font-size: 1em;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.conversation-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  justify-content: space-between;
  flex-shrink: 0;
}

/* 右侧聊天区域 */
.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
}

.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  margin-bottom: 10px; /* 为输入框留出空间 */
}

.chat-header {
  padding: 15px;
  border-bottom: 1px solid #eee;
  flex-shrink: 0;
  display: flex;
  align-items: center;
}

.chat-header h2 {
  margin: 0;
  color: #333;
  font-size: 1.2em;
  flex: 1;
}

.connecting-status {
  font-size: 0.8em;
  color: #6c757d;
  margin-left: 10px;
}

/* 消息显示区域 */
.chat-messages-container {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
  background: #f8f9fa;
  display: flex;
  flex-direction: column;
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 8px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 消息样式 */
.message {
  margin-bottom: 15px;
  display: flex;
  width: 100%;
}

.message.own-message {
  justify-content: flex-end;
}

.message.other-message {
  justify-content: flex-start;
}

.message-content {
  max-width: 80%;
  padding: 10px 15px;
  border-radius: 18px;
  background: white;
  box-shadow: 0 1px 2px rgba(0,0,0,0.1);
  word-wrap: break-word;
  word-break: break-word;
}

.message.own-message .message-content {
  background: #007bff;
  color: white;
}

.content {
  margin-bottom: 5px;
  line-height: 1.4;
  word-wrap: break-word;
  white-space: pre-wrap;
}

.timestamp {
  font-size: 0.75em;
  color: #6c757d;
  text-align: right;
}

.message.own-message .timestamp {
  color: rgba(255,255,255,0.7);
}

/* 独立的聊天输入区域 */
.chat-input-area {
  padding: 15px;
  background: white;
  border-top: 1px solid #eee;
  flex-shrink: 0;
  border-radius: 8px;
  box-shadow: 0 -2px 8px rgba(0,0,0,0.1);
}

.chat-input {
  width: 100%;
}

.no-messages {
  text-align: center;
  color: #6c757d;
  padding: 20px;
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.no-conversation-selected {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.loading-indicator {
  text-align: center;
  padding: 20px;
  color: #6c757d;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-main-container {
    height: calc(100vh - 80px);
  }
  
  .conversation-list {
    width: 250px;
    padding-right: 0;
  }
  
  .conversation-info h3 {
    font-size: 0.95em;
  }
  
  .message-content {
    max-width: 90%;
  }
}

@media (max-width: 480px) {
  .main-layout {
    flex-direction: column;
  }
  
  .conversation-list {
    width: 100%;
    height: 200px; /* 移动端固定高度 */
  }
  
  .chat-area {
    flex: 1;
  }
  
  .chat-input-area {
    padding: 10px;
  }
}
</style>